package com.ehualu.getes.until;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.*;

public class EsUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsUtil.class);


    /**
     * 获取client连接
     */
//    public RestHighLevelClient getHighLevelClient(String host, int port, String schema) {
//       /* //单个ip创建方式
//        HttpHost  httpHost= new HttpHost(host, port, schema);
//        RestClientBuilder builder = RestClient.builder(httpHost);
//        RestHighLevelClient  client = new RestHighLevelClient(builder);
//        return client;*/
//        String[] ipArr = host.split(",");
//        HttpHost[] httpHosts = new HttpHost[ipArr.length];
//        for (int i = 0; i < ipArr.length; i++) {
//            httpHosts[i] = new HttpHost(ipArr[i], port, schema);
//        }
//        RestClientBuilder builder = RestClient.builder(httpHosts);
//        RestHighLevelClient client = new RestHighLevelClient(builder);
//        return client;
//    }

    public RestClient getLowLevelClient(RestHighLevelClient client) {
        return client.getLowLevelClient();
    }


    public void getshij(String starttime, String endTimeStr, String index, String kkid, RestHighLevelClient client) {
        try {

            String indexName = index;

            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//			sourceBuilder.from(0); // 默认0
            sourceBuilder.size(10000);// 默认10条

            QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                    .must(QueryBuilders.termQuery("caddresscode", kkid))
                    .must(QueryBuilders.rangeQuery("createtime").from(starttime).to(endTimeStr));
            sourceBuilder.query(queryBuilder);
            searchRequest.source(sourceBuilder);
            SearchResponse response = client.search(searchRequest);
            SearchHits hits = response.getHits();
            SearchHit[] searchHits = hits.getHits();
            int sl = searchHits.length;
            System.out.println("查询数据量：" + sl);
            for (SearchHit hit : searchHits) {


                Map<String, Object> sourceAsMap = hit.getSourceAsMap();// 获取查询结果json

                String strccarnumber = (String) sourceAsMap.get("ccarnumber");
                String strid = (String) sourceAsMap.get("dtid");

                System.out.println("strccarnumber:" + strccarnumber);
                System.out.println("strid:" + strid);
//				log.info("索引：" + index + ",类型：" + type + ",ID：" + id + ",得分：" + score + "," + sourceAsMap);
//				return sourceAsMap.get("pic1") + "";
            }
            System.out.println("循环*****结束");

//			return pic;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    public int getshij2(String starttime, String endTimeStr, String index, String kkid, RestHighLevelClient client) {
        try {

            String indexName = index;

            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//			sourceBuilder.from(0); // 默认0
            sourceBuilder.size(10000);// 默认10条

            QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                    .must(QueryBuilders.termQuery("caddresscode", kkid))
                    .must(QueryBuilders.rangeQuery("createtime").from(starttime).to(endTimeStr));
            sourceBuilder.query(queryBuilder);
            searchRequest.source(sourceBuilder);
            SearchResponse response = client.search(searchRequest);
            SearchHits hits = response.getHits();
            SearchHit[] searchHits = hits.getHits();
            int sl = searchHits.length;
            System.out.println("查询数据量：" + sl);
            for (SearchHit hit : searchHits) {


                Map<String, Object> sourceAsMap = hit.getSourceAsMap();// 获取查询结果json

                String strccarnumber = (String) sourceAsMap.get("ccarnumber");
                String strid = (String) sourceAsMap.get("dtid");

                System.out.println("strccarnumber:" + strccarnumber);
                System.out.println("strid:" + strid);
//				log.info("索引：" + index + ",类型：" + type + ",ID：" + id + ",得分：" + score + "," + sourceAsMap);
//				return sourceAsMap.get("pic1") + "";
            }
            System.out.println("循环*****结束");
            return sl;

//			return pic;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return 0;
    }

    /**
     * 国道:G105 道路代码
     * 48288
     * 48198
     * 48181
     * 48229
     * 48072
     * 48088
     * 10105
     * 48168
     * 48266
     * 48281
     * 48282
     * 48151
     * 48153
     * 48300
     * 46688
     * 46077
     * 67102
     * 46545
     * 48157
     * 48164
     */
    public Map<String, String> getGliuluntil(String index, String nowtime, String dlm, String fx, Map<String, Integer> dlkknummap, RestHighLevelClient client) {

        String res;
//        设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//        设置时区
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

//时间戳转成date类型
        long lt = new Long(nowtime);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        System.out.println("********当前时间转换时区后*********" + res);

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

//        时间向前推七天
        cal.add(Calendar.DATE, -7);

        Date dabef = cal.getTime();

        String outtime = simpleDateFormat.format(dabef);

        System.out.println("********当前时间转换时区并往前推7天后*********" + outtime);

        QueryBuilder queryBuilderG105 = QueryBuilders.boolQuery()
                .must(QueryBuilders.termsQuery("dldm", "48288", "48198", "48181", "48229", "48072", "48088", "10105", "48168", "48266", "48281", "48282", "48151", "48153", "48300", "46688", "46077", "67102", "46545", "48157", "48164"))
//                .must(QueryBuilders.termQuery("xsfx", fx))
                .must(QueryBuilders.rangeQuery("createtime").from(outtime).to(res));

//        String indexName = index;

        Long countnum = sumavg(index, client, queryBuilderG105);
        System.out.println("********countnum*********" + countnum);


        return null;


//
//        SearchRequest searchRequest = new SearchRequest(indexName);
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//			sourceBuilder.from(0); // 默认0
//        sourceBuilder.size(10000);// 默认10条


//        sourceBuilder.query(queryBuilderG105);
//        searchRequest.source(sourceBuilder);
//        SearchResponse response = null;
//        try {
//            response = client.search(searchRequest);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        SearchHits hits = response.getHits();
//        Long rtlh=  response.getHits().getTotalHits();
//        System.out.println(rtlh);
//
//        System.out.println("循环*****结束");
//
//        return null;
    }

    //当前小时每个国道单方向
    public Long getGliuluntilforh(String index, String nowtime, String fx, String[] dldmsz, Integer dlkksl, RestHighLevelClient client) {


//        Map<String, Long> evgdavgmap = new HashMap<>();

//时间戳转成date类型
        long lt = new Long(nowtime);
        Date date = new Date(lt);

        SimpleDateFormat simh = new SimpleDateFormat("yyyy-MM-dd'T'HH");
////        设置时区
        simh.setTimeZone(TimeZone.getTimeZone("GMT"));

        String resh = simh.format(date);
        String reshstart = resh + ":00:00.000Z";
        String reshend = resh + ":59:59.999Z";

        System.out.println("********当前时间小时开始ES*********" + reshstart);
        System.out.println("********当前时间小时结束ES*********" + reshend);


        QueryBuilder queryBuilder = QueryBuilders.boolQuery()
//                    termsQuery 函数用了变长变量 传多个 string可以 传数组也行
                .must(QueryBuilders.termsQuery("dldm", dldmsz))
                .must(QueryBuilders.termQuery("xsfx", fx))
                .must(QueryBuilders.rangeQuery("createtime").from(reshstart).to(reshend));


        Long countnum = sumavg(index, client, queryBuilder);


        Integer kkcount = dlkksl;
//        System.out.println("******道路名称*******" + mapKey);
        System.out.println("******道路过车统计总数*******" + countnum);
        System.out.println("******道路卡口数*******" + kkcount);
        Long gcavg = countnum / kkcount;


        System.out.println("******道路过车平均*******" + gcavg);
        return gcavg;


//        evgdavgmap.put(mapKey, gcavg);


//        for (Map.Entry<String, String[]> entry : dldmmap.entrySet()) {
//            String mapKey = entry.getKey();
//            String[] mapValue = entry.getValue();
////            System.out.println(mapKey + ":" + mapValue);
//
//
//            QueryBuilder queryBuilder = QueryBuilders.boolQuery()
////                    termsQuery 函数用了变长变量 传多个 string可以 传数组也行
//                    .must(QueryBuilders.termsQuery("dldm", mapValue))
//                    .must(QueryBuilders.termQuery("xsfx", fx))
//                    .must(QueryBuilders.rangeQuery("createtime").from(reshstart).to(reshend));
//
//
//            Long countnum = sumavg(index, client, queryBuilder);
//
//
//            Integer kkcount = dlkknummap.get(mapKey);
//            System.out.println("******道路名称*******" + mapKey);
//            System.out.println("******道路过车统计总数*******" + countnum);
//            System.out.println("******道路卡口数*******" + kkcount);
//            Long gcavg = countnum / kkcount;
//
//
//            System.out.println("******道路过车平均*******" + gcavg);
//
//
//            evgdavgmap.put(mapKey, gcavg);
//        }
//
//        return evgdavgmap;

    }


    public Long sumavg(String indexName, RestHighLevelClient client, QueryBuilder queryBuilder) {

        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        SearchHits hits = response.getHits();
        Long rtlh = response.getHits().getTotalHits();
        System.out.println("******统计条数******" + rtlh);

        return rtlh;
    }


    public void cphmpp(String index, String nowtime, String hphm, String fx, RestHighLevelClient client) {


        try {

            String starttime = "";

            String endTimeStr = "";


            String indexName = index;

            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//			sourceBuilder.from(0); // 默认0
//			sourceBuilder.size(100);// 默认10条

            QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                    .must(QueryBuilders.termQuery("ccarnumber", hphm))
                    .must(QueryBuilders.rangeQuery("createtime").from(starttime).to(endTimeStr));
            sourceBuilder.query(queryBuilder);
            searchRequest.source(sourceBuilder);
            SearchResponse response = client.search(searchRequest);
            SearchHits hits = response.getHits();
            Long rtlh = response.getHits().getTotalHits();
            System.out.println(rtlh);
            SearchHit[] searchHits = hits.getHits();
            int sl = searchHits.length;
            System.out.println("查询数据量：" + sl);

            Connection conn = DBConnection.getcon();

            OracleUtills oracleUtills=new OracleUtills();


//            原车牌 ES 查询集合
            for (SearchHit hit : searchHits) {


                Map<String, Object> sourceAsMap = hit.getSourceAsMap();// 获取查询结果json

                String strccarnumber = (String) sourceAsMap.get("ccarnumber");
                String strid = (String) sourceAsMap.get("dtid");

//                卡口id
                String sbid = (String) sourceAsMap.get("caddresscode");

//                卡口名称
                String sbmc = (String) sourceAsMap.get("ccollectionaddress");


//                过车时间
                String gcsj = (String) sourceAsMap.get("createtime");


//                卡口经度
                String jd = (String) sourceAsMap.get("jd");

//                卡口维度
                String wd = (String) sourceAsMap.get("wd");






                System.out.println("strccarnumber:" + strccarnumber);
                System.out.println("strid:" + strid);
//				log.info("索引：" + index + ",类型：" + type + ",ID：" + id + ",得分：" + score + "," + sourceAsMap);
//				return sourceAsMap.get("pic1") + "";
            }
            System.out.println("循环*****结束");
            if (conn != null) {

                conn.close();

            }
//			return pic;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }


    }


    /**
     * 关闭连接
     */
//    public void close(RestHighLevelClient client) {
//        if (client != null) {
//            try {
//                client.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
